<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{$t('notification.index.queryCriteria')}}</span></el-col>
      </el-row>
      <el-form :inline="true" :model="listQuery" style="padding:0 20px">
        <el-row>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('notification.index.notificationType')}}</div>
              <dict-select v-model="listQuery.type" code="notificationType"></dict-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('notification.index.announcementState')}}</div>
              <dict-select v-model="listQuery.status" code="notificationStatus" codeDefault="allAnnouncements"></dict-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('notification.index.notificationTitle')}}</div>
              <el-input v-model="listQuery.title" :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('notification.index.closeDate')}}</div>
              <el-date-picker
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                v-model="listQuery.createTime"
                type="daterange"
                range-separator="-"
                :start-placeholder="$t('notification.index.placeholder.startTime')"
                :end-placeholder="$t('notification.index.placeholder.endTime')">
              </el-date-picker>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('notification.index.publisher')}}</div>
              <el-input v-model="listQuery.publisher" :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('notification.index.receiver')}}</div>
              <dict-select v-model="listQuery.receiver" code="receiver"></dict-select>
            </div>
          </el-col>
          <el-col style="margin-top: 20px;text-align: center">
            <div type="primary" class="yt-btn yt-btn-ys" v-if="hasQuery" @click="getList">{{ $t("button.search")}}</div>
            <div type="primary" class="yt-btn yt-ml8" v-if="hasQuery" @click="reset">{{ $t("button.reset")}}</div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--公告列表-->
    <div class="yt-data-list">
      <div class="yt-list-title">
        <span>{{$t('notification.index.notificationList')}}</span>
      </div>
      <div class="yt-list-content">
        <div class="list-operation">
          <!--新增-->
          <div v-if="hasAdd" class="yt-btn yt-btn-ys" type="primary" @click="newly">{{ $t("button.new")}}</div>
          <!--失效-->
          <div v-if="hasInvalid" class="yt-btn yt-ml8" type="primary" @click="handlePreserve('edit')">
            {{$t('notification.index.button.invalid')}}
          </div>
          <!--删除-->
          <div v-if="hasDelete" class="yt-btn yt-ml8" type="danger" @click="handlePreserve('del')">{{ $t("button.delete")}}</div>
        </div>

        <el-table class="yt-table" v-loading.body="listLoading" :data="notificationData" :empty-text="$t('placeholder.emptyText')" highlight-current-row border v-loading="loading" @selection-change="handleSelectionChange" max-height="600">
          <el-table-column align="center" type="selection" width="60" prop="id"/>
          <el-table-column align="center" type="index" :label="$t('notification.index.serialNumber')" width="60"/>
          <!--公告类型-->
          <el-table-column align="center" :label="$t('notification.index.notificationType')" class-name="pd" min-width="130">
            <template slot-scope="scope">
              <div>{{ config[scope.row.type] }}</div>
            </template>
          </el-table-column>
          <!--公告名称-->
          <el-table-column align="center" :label="$t('notification.index.notificationTitle')" min-width="130">
            <template slot-scope="scope">
              <div style="text-decoration: underline;color: #6dcaa8;cursor: pointer;" @click="update(scope.row)">{{ scope.row.title }}</div>
            </template>
          </el-table-column>
          <!--状态-->
          <el-table-column prop="status" align="center" :label="$t('notification.index.state')" min-width="100"></el-table-column>
          <!--建立者-->
          <el-table-column prop="publisher" align="center" :label="$t('notification.index.publisher')" min-width="100"></el-table-column>
          <!--发布时间-->
          <el-table-column prop="createTime" align="center" :label="$t('notification.index.releaseTime')" min-width="140"></el-table-column>
          <!--接收人-->
          <el-table-column prop="receiverName" align="center" :label="$t('notification.index.receiver')" min-width="100"></el-table-column>
        </el-table>
        <div class="pagination-container" v-if="hasQuery">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background :current-page.sync="listQuery.page" :page-sizes="[10, 20, 30, 50, 100, 200]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    notificationQuery,
    invalid,
    deleteNotification
  } from '@/api/e-formula/notification/index';
  import { lookNotification } from '@/api/admin/notification';
  import { mapGetters } from 'vuex';

  export default {
    name: 'notification',
    components: {
      'dict-select': () => import('@/components/Dict/dictValueSelect')
    },
    data() {
      return {
        hasAdd: false,
        hasInvalid: false,
        hasDelete: false,
        hasQuery: false,
        selectionList: [],
        listAll: this.$store.getters.allDic,
        listMapAll: this.$store.getters.allMapDic,
        dialogForm: {
          id: '',
          country: '',
          bg: '',
          bu: '',
          clientType: '',
          territory: '',
          client: '',
          bdNo: '',
          bdName: '',
          contactWindow: '',
          decisionMaker: '',
          sales: '',
          presales: '',
          startDate: '',
          endDate: '',
          targetQuarter: '',
          targetMonth: '',
          estimatedBudget: '',
          estimatedCost: '',
          status: '',
          actionsSales: '',
          actionsPresales: '',
          isFinish: '',
          projectNo: ''
        },
        config: Config.I18n,
        loading: false,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10,
          notificationType: undefined, // 公告类型
          notificationStatus: undefined, // 公告状态
          notificationTitle: undefined, // 公告名称
          createTime: [],
          dateTime: undefined,
          startTime: undefined,
          endTime: undefined,
          publisher: undefined, // 建立者
          receiver: undefined // 接收人
        },
        notificationData: [],
        //  修改的数据
        modification: []
      };
    },
    created() {
      console.log('this.elements', this.elements)
      this.hasDelete = this.elements['notificationManager:btn_del'];
      this.hasInvalid = this.elements['notificationManager:btn_invalid'];
      this.hasAdd = this.elements['notificationManager:btn_add'];
      this.hasQuery = this.elements['notificationManager:btn_view'];
    },
    computed: {
      ...mapGetters([
        'elements'
      ])
    },
    mounted() {
      this.getQuery()
      this.getList();
    },
    methods: {
      getQuery() {
        const notificationListQuery = window.sessionStorage.getItem('notificationListQuery');
        if (notificationListQuery) {
          this.listQuery = JSON.parse(notificationListQuery);
        }
      },
      reset() {
        this.listQuery = {};
        this.getList();
      },
      getList() {
        this.listLoading = true;

        if (this.listQuery.createTime && this.listQuery.createTime.length > 0) {
          this.listQuery.startTime = this.listQuery.createTime[0];
          this.listQuery.endTime = this.listQuery.createTime[1];
        }
        notificationQuery(this.listQuery).then(res => {
          res.data.data.rows.forEach(key => {
            if (key.status === 'releaseFinish') {
              key.status = this.$t('notification.index.tips.releaseFinish');
            } else if (key.status === 'releaseWait') {
              key.status = this.$t('notification.index.tips.releaseWait');
            }
          });
          this.listLoading = false;
          this.notificationData = res.data.data.rows;
          this.notificationData.forEach(x => {
            x.receiverName = this.listMapAll.receiver[x.receiver];
          });
          this.total = res.data.data.total;
        });
      },
      add() {
        this.$router.push({ path: '/baseManager/notificationManagerEdit', query: { title: 'add' } })
      },
      newly() {
        this.$router.push({ path: '/baseManager/notificationManagerEdit', query: { title: 'add' } })
      },
      handlePreserve(val) {
        console.log(this.modification);
        if (val === 'del') {
          if (this.modification.length > 0) {
            const arr = []; // 存放已修改的
            this.modification.forEach(item => {
              arr.push(item.id);
            });
            this.$confirm(this.$t('notification.index.tips.delete'), this.$t('notification.index.tips.tips'), {
              confirmButtonText: this.$t('notification.index.tips.determine'),
              cancelButtonText: this.$t('notification.index.tips.cancel'),
              type: 'warning',
              center: true
            })
              .then(action => {
                if (action === 'confirm') {
                  deleteNotification(arr).then(res => {
                    this.$notify({
                      title: res.status === 200 ? this.$t('notification.index.tips.deleteSuccess') : this.$t('notification.index.tips.fail'),
                      message: res.status === 200 ? this.$t('notification.index.tips.deleteSuccess') : res.message,
                      type: res.status === 200 ? 'success' : 'warning'
                    });
                    this.getList();
                  });
                }
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: this.$t('notification.index.tips.cancelled')
                });
              });
          } else {
            this.$notify({
              title: this.$t('notification.index.tips.fail'),
              message: this.$t('notification.index.tips.aRecord'),
              type: 'warning'
            });
          }
        } else {
          //  失效功能
          if (this.modification.length > 0) {
            const arr = []; // 存放已修改的
            this.modification.forEach(item => {
              arr.push(item.id);
            });
            this.$alert(this.$t('notification.index.tips.cannotCancel'), this.$t('notification.index.tips.tips'), {
              confirmButtonText: this.$t('notification.index.tips.confirmInvalid'),
              // eslint-disable-next-line no-unused-vars
              callback: action => {
                console.log(arr, 'arr');
                invalid(arr).then(res => {
                  this.$notify({
                    title: res.status === 200 ? this.$t('notification.index.tips.editSuccess') : this.$t('notification.index.tips.fail'),
                    message: res.status === 200 ? this.$t('notification.index.tips.editSuccess') : this.$t('notification.index.tips.fail'),
                    type: res.status === 200 ? 'success' : 'warning'
                  });
                  this.getList();
                });
              }
            });
          } else {
            this.$notify({
              title: this.$t('notification.index.tips.fail'),
              message: this.$t('notification.index.tips.aRecord'),
              type: 'warning'
            });
          }
        }
      },
      dele() {
        const list = [];
        for (
          let i = 0, flag = true, len = this.modification.length;
          i < len;
          flag ? i++ : i
        ) {
          if (this.modification[i] && this.modification[i].status === '已发布' || this.modification[i].status === '已發布') {
            this.$alert(this.$t('notification.index.tips.releaseFinishDelete'), this.$t('notification.index.tips.tips'), {
              confirmButtonText: this.$t('notification.index.tips.determine'),
              // eslint-disable-next-line no-unused-vars
              callback: action => {
                lookNotification().then(res => {
                  console.log(res);
                });
              }
            });
            this.modification.splice(i, 1);
            flag = false;
          } else {
            flag = true;
            if (this.modification[i]) {
              list.push(this.modification[i].id);
            }
          }
        }
      },
      handleSelectionChange(val) {
        this.modification = val;
      },
      update(row) {
        if (!hasQuery) {
          return
        }
        console.log(row)
        if (row.status === '待发布' || row.status === '待發布') {
          this.$router.push({ path: '/baseManager/notificationManagerEdit', query: { title: 'update', id: row.id } })
        } else {
          this.$router.push({ path: '/baseManager/notificationManagerEdit', query: { title: 'check', id: row.id } })
        }
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('notificationListQuery', JSON.stringify(this.listQuery))
    }
  };
</script>

<style scoped>
</style>
